package com.wms.controller;


import cn.hutool.jwt.JWTUtil;
import com.wms.bean.ResultBean;
import com.wms.core.R;
import com.wms.dto.LoginDto;
import com.wms.entity.AddUser;
import com.wms.entity.User;
import com.wms.exception.V;
import com.wms.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "王奥鑫登录")
@RequestMapping("/api")
public class UserController {
    @Autowired
    UserService userService;
    @Value("${token.secret}")
    String secret;


    @ApiOperation("登录")
    @PostMapping ("/waxlogin")
    public ResultBean waxlogin(@Validated @RequestBody LoginDto loginDto, BindingResult result){
        V.validate(result);

        User user=userService.querryByMobile(loginDto.getMobile());
        //根据用户名查是否存在
        if (user == null){
            System.out.println("该用户不存在");
            return R.fail("该用户不存在");
        }
        //验证密吗
        String mima= DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if (!user.getPassword().equals(mima)){
        //   throw new RuntimeException("账号或密码错误");
            return R.fail("账号或密码错误");
        }
        //冻结状态
        if (user.getStatus()==0){
            return R.fail("账号已经冻结");
        }

        //生成token
        Map payload=new HashMap();
        payload.put("id",user.getId());
        payload.put("name",user.getName());
        payload.put("mobile",user.getMobile());
        String token=JWTUtil.createToken(payload,secret.getBytes());
        payload.put("token",token);
        return R.success("登录成功",payload);
    }



    @PostMapping("/waxAddUser")
    @ApiOperation("新增用户")
    public ResultBean waxAddUser(@Valid @RequestBody AddUser user){
        int n=userService.addUser(user);
        return R.success("新增用户",n);
    }
}